package lib.quasar.db.helper;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import org.greenrobot.greendao.database.Database;

import lib.quasar.db.gen.ChatDao;
import lib.quasar.db.gen.DaoMaster;
import lib.quasar.db.gen.HttpDao;
import lib.quasar.db.gen.MessageDao;
import lib.quasar.db.gen.UserDao;

/**
 * 用于数据库升级的工具类
 * <p>
 * 1、新建临时表   generateTempTables(db, daoClasses);
 * 2、创建新表     createAllTables(db, false, daoClasses);
 * 3、临时表数据写入新表，删除临时表   restoreData(db, daoClasses);
 * <p>
 * 步骤：
 * 比如升级SubscriberOpenEntity表，需要添加字段SEX；
 * 1、需要在build.gradle里面修改数据库版本号为2
 * 2、在UserTwo里面添加字段SEX，接着Make-Project
 * 3、运行项目，就会走升级的OnUpgrade方法；
 */
public class DbUpdataHelper extends DaoMaster.OpenHelper {

    private final String TAG = DbUpdataHelper.class.getSimpleName();

    public DbUpdataHelper(Context context, String dbName, SQLiteDatabase.CursorFactory factory) {
        super(context, dbName, factory);
    }

    @Override
    public void onUpgrade(Database db, int oldVersion, int newVersion) {

        if (oldVersion == newVersion) {
            Log.e(TAG, "oldVersion = " + oldVersion + ", newVersion = " + newVersion + ", 数据库是最新版本");
        } else {
            Log.e(TAG, "oldVersion = " + oldVersion + ", newVersion = " + newVersion + ", 数据库升级版本");
            for (int i = oldVersion; i < newVersion; i++) {
                try {
                    DbMergeHelper.migrate(db, HttpDao.class);
                    DbMergeHelper.migrate(db, UserDao.class);
                    DbMergeHelper.migrate(db, ChatDao.class);
                    DbMergeHelper.migrate(db, MessageDao.class);
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }
        }
    }
}